package com.generalbackend.role.util;

import com.generalbackend.common.model.entity.Property;
import com.generalbackend.common.util.PropertyManage;
import com.generalbackend.common.util.SystemProfileUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tim.xie
 * @date 2021/12/14 13:47
 */
public class RoleConf {
    private static final String PATH = SystemProfileUtil.getConfPath() + SystemProfileUtil.getFileSeparator() + "role.conf";
    private static volatile PropertyManage propertyManage;
    private static volatile Map<String, List<String>> permissionMap = new HashMap<>();

    /**
     * 加载或重新加载role.conf配置
     */
    public static void loadProperty() {
        PropertyManage property = new PropertyManage();
        try {
            FileReader fileReader = new FileReader(new File(PATH));
            property.load(new BufferedReader(fileReader));
        } catch (IOException e) {
            e.printStackTrace();
        }
        propertyManage = property;
        propertyManage.values()
                .stream()
                .filter(e -> !((Property) e).getName().equals("all") && !((Property) e).getName().equals("allrole") && !((Property) e).getName().equals("common"))
                .collect(Collectors.toList())
                .forEach(e -> Arrays.stream(((Property) e).getValue().split(","))
                        .forEach(u -> {
                            List<String> permissionList = permissionMap.getOrDefault(u, new ArrayList<>());
                            permissionList.add(((Property) e).getName());
                            permissionMap.put(u, permissionList);
                        }));
    }

    /**
     * 根据权限获取对应url
     * @param permission
     * @return
     */
    public static String getPermissionUrl(String permission) {
        return Optional.ofNullable(propertyManage)
                .map(m -> m.getProperty(permission))
                .map(Property::getValue)
                .orElse("");
    }

    /**
     * 通过api获取对应菜单
     * @param api
     * @return
     */
    public static List<String> getPermissionByApi(String api) {
        if(permissionMap.containsKey(api)) {
            return permissionMap.get(api);
        } else {
            for(String key : permissionMap.keySet()) {
                if(api.startsWith(key)) {
                    return permissionMap.get(key);
                }
            }
        }
        return new ArrayList<>();
    }
}
